﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

using Microsoft.Practices.Unity;

using Happy.Bootstrap;
using Happy.ExtentionMethods;

namespace Happy.Bootstrap.Unity
{
    /// <summary>
    /// 按照约定注册服务插件。
    /// </summary>
    public sealed class RegisterServiceByConventionPlugin : IBootstrapPlugin
    {
        private readonly IUnityContainer _unityContainer;
        private readonly List<IConventionRegister> _convertions = new List<IConventionRegister>();

        /// <summary>
        /// 构造方法。
        /// </summary>
        public RegisterServiceByConventionPlugin(IUnityContainer unityContainer)
        {
            unityContainer.MustNotNull("unityContainer");

            _unityContainer = unityContainer;
        }

        /// <inheritdoc />
        public void Start(IBootstrapService bootstrapService, Assembly assembly)
        {
            bootstrapService.MustNotNull("bootstrapService");
            assembly.MustNotNull("assembly");

            foreach (var type in assembly.GetTypes())
            {
                if (type.IsAbstract || type.IsInterface)
                {
                    continue;
                }

                var isRegisted = false;

                foreach (var convertion in _convertions)
                {
                    isRegisted = isRegisted || convertion.Register(_unityContainer, type);
                }

                if (!isRegisted)
                {
                    _unityContainer.RegisterTypeForAllInterface(type, () => new TransientLifetimeManager());
                }
            }
        }

        /// <summary>
        /// 注册约定。
        /// </summary>
        public RegisterServiceByConventionPlugin AddConvertion(IConventionRegister convertion)
        {
            convertion.MustNotNull("convertion");

            _convertions.Add(convertion);

            return this;
        }
    }
}
